//
//  ECUButton.m
//  Edu_iOS2018
//
//  Created by apple on 2018/1/3.
//  Copyright © 2018年 yanyan. All rights reserved.
//

#import "ECUButton.h"
#import "UIImage+Color.h"

@implementation ECUButton

-(void)openCountdown{
    
    __block NSInteger time = 59; //倒计时时间
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    
    dispatch_source_set_event_handler(_timer, ^{
        
        if(time <= 0){ //倒计时结束，关闭
            
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //设置按钮的样式
                [self setTitle:@"获取验证码" forState:UIControlStateNormal];
                [self setTitleColor:[UIColor colorWithHexString:@"313131"] forState:UIControlStateNormal];
                self.userInteractionEnabled = YES;
            });
        }else{
            
            int seconds = time % 60;
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //设置按钮显示读秒效果
                [self setTitle:[NSString stringWithFormat:@"%d", seconds] forState:UIControlStateNormal];
                [self setTitleColor:[UIColor colorWithHexString:@"979797"] forState:UIControlStateNormal];
                self.userInteractionEnabled = NO;
            });
            time--;
        }
    });
    dispatch_resume(_timer);
}

-(void)setHighlighted:(BOOL)highlighted{
    //如果加了下面这句话就和我们没有写这个方法是一样的，所以想取消高亮状态就要把下面这句话给注释掉
    //[super setHighlighted:highlighted];  
}

@end
